package com.example.malldemo.service.impl;

import com.example.malldemo.mbg.mapper.UmsPermissionMapper;
import com.example.malldemo.mbg.model.UmsPermission;
import com.example.malldemo.mbg.model.UmsPermissionExample;
import com.example.malldemo.mbg.model.UmsPermissionNode;
import com.example.malldemo.service.UmsPermissionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UmsPermissionServiceImpl implements UmsPermissionService {
    @Resource
    private UmsPermissionMapper permissionMapper;

    @Override
    public List<UmsPermissionNode> treeList() {
        List<UmsPermission> permissionList = permissionMapper.selectByExample(new UmsPermissionExample());
        return permissionList.stream()
                .filter(permission->permission.getPid().equals(0L))
                .map(permission->convert(permission,permissionList))
                .collect(Collectors.toList());
    }

    private UmsPermissionNode convert(UmsPermission permission, List<UmsPermission> permissionList) {
        UmsPermissionNode node = new UmsPermissionNode();
        BeanUtils.copyProperties(permission,node);
        List<UmsPermissionNode> children = permissionList.stream()
                .filter(subPermission -> subPermission.getPid().equals(permission.getId()))
                .map(subPermission ->convert(subPermission,permissionList))
                .collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
